#include <stdlib.h>
#include <stdio.h>
#include "minstack.h"

void minStackInit(MinStack *stack, int maxSize) {
  stack->data = (MinStackElement *)malloc(sizeof(MinStackElement)*maxSize);
  if (NULL == stack->data) {
    fprintf(stderr, "MinStack Init failed!");
    exit(1);
  }
  
  stack->size = maxSize;
  stack->top = 0;
  
  return;
}

void minStackDestroy(MinStack *stack) {
  free(stack->data);

  return;
}

void minStackPush(MinStack *stack, int d) {
  MinStackElement *p = NULL;
  if (stack->top == stack->size)
    fprintf(stderr, "out of stack space.");
  
  p = stack->data + stack->top;
  p->data = d;
  p->min = (0 == stack->top ? d : stack->data[stack->top - 1].min);
  if (p->min > d)
    p->min = d;
  
  ++stack->top;

  return;
}

int minStackPop(MinStack *stack) {
  if (0 == stack->top)
    fprintf(stderr, "stack is empty.");
  
  return stack->data[--stack->top].data;
}

int minStackMin(MinStack *stack) {
  if (0 == stack->top)
    fprintf(stderr, "stack is empty.");
  
  return stack->data[stack->top-1].min;
}
